package com.example.util;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

public class SpelParser {

    private static final ExpressionParser parser=new SpelExpressionParser();

    public static String getKey(String key,String[] params,Object[] args){
        Expression expression = parser.parseExpression(key);
        if (args.length<=0){
            return null;
        }
        StandardEvaluationContext context = new StandardEvaluationContext();
        for (int i = 0; i < args.length; i++) {
            context.setVariable(params[i],args[i]);
        }
        return expression.getValue(context,String.class);
    }

    public static String getKey(String key, ProceedingJoinPoint joinPoint){
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        Parameter[] parameters = method.getParameters();
        String[] paramNames=new String[parameters.length];
        for (int i = 0; i < parameters.length; i++) {
            paramNames[i]=parameters[i].getName();
        }
        return getKey(key,paramNames, joinPoint.getArgs());
    }

    public static String getKey(String key,String param,Object arg){
        Expression expression = parser.parseExpression(key);
        if (arg==null){
            return null;
        }
        StandardEvaluationContext context = new StandardEvaluationContext();
        context.setVariable(param,arg);
        return expression.getValue(context,String.class);
    }

    public static <T> T getKey(String key,String param,Object arg,Class<T> clazz){
        Expression expression = parser.parseExpression(key);
        if (arg==null){
            return null;
        }
        StandardEvaluationContext context = new StandardEvaluationContext();
        context.setVariable(param,arg);
        return expression.getValue(context,clazz);
    }
}
